#region Copyright (c) 2006-2009 Widgetsphere LLC, All Rights Reserved
//--------------------------------------------------------------------- *
//                          Widgetsphere  LLC                           *
//             Copyright (c) 2006-2009 All Rights reserved              *
//                                                                      *
//                                                                      *
//This file and its contents are protected by United States and         *
//International copyright laws.  Unauthorized reproduction and/or       *
//distribution of all or any portion of the code contained herein       *
//is strictly prohibited and will result in severe civil and criminal   *
//penalties.  Any violations of this copyright will be prosecuted       *
//to the fullest extent possible under law.                             *
//                                                                      *
//THE SOURCE CODE CONTAINED HEREIN AND IN RELATED FILES IS PROVIDED     *
//TO THE REGISTERED DEVELOPER FOR THE PURPOSES OF EDUCATION AND         *
//TROUBLESHOOTING. UNDER NO CIRCUMSTANCES MAY ANY PORTION OF THE SOURCE *
//CODE BE DISTRIBUTED, DISCLOSED OR OTHERWISE MADE AVAILABLE TO ANY     *
//THIRD PARTY WITHOUT THE EXPRESS WRITTEN CONSENT OF WIDGETSPHERE LLC   *
//                                                                      *
//UNDER NO CIRCUMSTANCES MAY THE SOURCE CODE BE USED IN WHOLE OR IN     *
//PART, AS THE BASIS FOR CREATING A PRODUCT THAT PROVIDES THE SAME, OR  *
//SUBSTANTIALLY THE SAME, FUNCTIONALITY AS ANY WIDGETSPHERE PRODUCT.    *
//                                                                      *
//THE REGISTERED DEVELOPER ACKNOWLEDGES THAT THIS SOURCE CODE           *
//CONTAINS VALUABLE AND PROPRIETARY TRADE SECRETS OF WIDGETSPHERE,      *
//INC.  THE REGISTERED DEVELOPER AGREES TO EXPEND EVERY EFFORT TO       *
//INSURE ITS CONFIDENTIALITY.                                           *
//                                                                      *
//THE END USER LICENSE AGREEMENT (EULA) ACCOMPANYING THE PRODUCT        *
//PERMITS THE REGISTERED DEVELOPER TO REDISTRIBUTE THE PRODUCT IN       *
//EXECUTABLE FORM ONLY IN SUPPORT OF APPLICATIONS WRITTEN USING         *
//THE PRODUCT.  IT DOES NOT PROVIDE ANY RIGHTS REGARDING THE            *
//SOURCE CODE CONTAINED HEREIN.                                         *
//                                                                      *
//THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE.              *
//--------------------------------------------------------------------- *
#endregion
using System;
using System.Drawing;
using System.Collections;
using Widgetsphere.Generator.Common.GeneratorFramework;
using System.Windows.Forms;
using Widgetsphere.Generator.Common.Util;
using Widgetsphere.Generator.Common.Forms;
using System.Xml;

namespace Widgetsphere.Generator.Models
{
  public class CustomStoredProcedureColumnCollectionController : BaseModelObjectController
  {
    #region Member Variables

    private ContextMenu PopupMenu = null;
    private ListView ControllerListView = null;

    #endregion

    #region Constructor

    protected internal CustomStoredProcedureColumnCollectionController(IModelObject modelObject)
      : base(modelObject)
    {
    }

    #endregion

    #region BaseModelObjectController Members

    public override ModelObjectTreeNode Node
    {
      get
      {
        if(_node == null)
        {
          _node = new CustomStoredProcedureColumnCollectionNode(this);
        }
        return _node;
      }
    }

    public override ModelObjectUserInterface UIControl
    {
      get
      {
        if(this.UserInterface == null)
        {
          PanelUIControl ctrl = new PanelUIControl();
          ControllerListView = new ListView();
          ControllerListView.View = View.Details;
          ControllerListView.HideSelection = false;
          ControllerListView.FullRowSelect = true;
          ControllerListView.Dock = DockStyle.Fill;
          ControllerListView.Columns.Add("Name", 100, HorizontalAlignment.Left);
					ControllerListView.Columns.Add("Code Facade", 100, HorizontalAlignment.Left);
          ControllerListView.Columns.Add("Allow Null", 100, HorizontalAlignment.Left);
          ControllerListView.Columns.Add("Type", 100, HorizontalAlignment.Left);
          ControllerListView.Columns.Add("Length", 50, HorizontalAlignment.Right);
          System.Type[] typeList = new System.Type[] { typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(int) };
          ListViewComparer comparer = new ListViewComparer(ControllerListView, typeList);
          ControllerListView.ListViewItemSorter = comparer;
          comparer.Column = 0;
          ControllerListView.Sorting = SortOrder.Ascending;
          ControllerListView.SmallImageList = Widgetsphere.Generator.ImageHelper.GetImageList();
          ctrl.MainPanel.Controls.Add(ControllerListView);
          ctrl.Dock = DockStyle.Fill;

          ControllerListView.Sort();
          ControllerListView.MouseUp += new MouseEventHandler(listView_MouseUp);
          ControllerListView.KeyUp += new KeyEventHandler(listView_KeyUp);
          ControllerListView.DoubleClick += new EventHandler(listView_DoubleClick);

          PopupMenu = new ContextMenu();
          ControllerListView.ContextMenu = PopupMenu;
          MenuItem menuDelete = new MenuItem("Delete");
          menuDelete.Click += new EventHandler(menuDelete_Click);
          PopupMenu.MenuItems.Add(menuDelete);

          this.UserInterface = ctrl;
        }

				//Load the list
				ControllerListView.Items.Clear();
				foreach (Reference reference in (ReferenceCollection)this.Object)
				{
					CustomStoredProcedureColumn customStoredProcedureColumn = ((CustomStoredProcedureColumn)reference.Object);
					ListViewItem newItem = new ListViewItem(customStoredProcedureColumn.Name);
					newItem.ImageIndex = ImageHelper.GetImageIndex(ImageConstants.CustomStoredProcedureColumn);

					newItem.Tag = reference;
					newItem.Name = reference.Key;
					newItem.SubItems.Add(customStoredProcedureColumn.CodeFacade);
					newItem.SubItems.Add(customStoredProcedureColumn.AllowNull.ToString());
					newItem.SubItems.Add(customStoredProcedureColumn.Type.ToString().ToLower());
					newItem.SubItems.Add(customStoredProcedureColumn.Length.ToString());
					ControllerListView.Items.Add(newItem);
				}

        return this.UserInterface;
      }
    }

    private void listView_DoubleClick(object sender, System.EventArgs e)
    {
      if(this.ControllerListView.SelectedItems.Count == 1)
      {
        ListViewItem item = this.ControllerListView.SelectedItems[0];
        TreeNode[] nodeList = this.Node.Nodes.Find(((Reference)item.Tag).Key, false);
        if(nodeList.Length > 0)
        {
          if(this.Node.TreeView != null)
            this.Node.TreeView.SelectedNode = nodeList[0];
        }
      }
    }

    private void listView_KeyUp(object sender, KeyEventArgs e)
    {
      if(e.KeyCode == Keys.Delete)
      {
        menuDelete_Click(null, null);
      }
    }

    private void listView_MouseUp(object sender, MouseEventArgs e)
    {
      if(e.Button == MouseButtons.Right)
      {
        PopupMenu.Show((ListView)sender, new Point(e.X, e.Y));
      }
    }

    private void menuDelete_Click(object sender, System.EventArgs e)
    {
      if(MessageBox.Show("Do you wish to delete the selected items?", "Delete?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
        return;

      foreach(ListViewItem item in ControllerListView.SelectedItems)
        ((ReferenceCollection)this.Object).Remove(((Reference)item.Tag));

      //Remove the item from the listview
      for(int ii = ControllerListView.SelectedItems.Count - 1 ; ii >= 0 ; ii--)
      {
        //Remove the item from the tree
        this.Node.Nodes.Remove(this.Node.Nodes[ControllerListView.SelectedItems[ii].Name]);
        //Remove Listitem
        ControllerListView.Items.Remove(ControllerListView.SelectedItems[ii]);
      }

      this.Object.Root.Dirty = true;

    }

    public override MenuCommand[] GetMenuCommands()
    {
      MenuCommand mcAddCustomStoredProcedureColumn = new DefaultMenuCommand();
      mcAddCustomStoredProcedureColumn.Text = "New Column";
      mcAddCustomStoredProcedureColumn.Click += new EventHandler(AddCustomStoredProcedureColumnMenuClick);

			MenuCommand menuSep = new DefaultMenuCommand();
			menuSep.Text = "-";

			MenuCommand menuPaste = new DefaultMenuCommand();
			menuPaste.Text = "Paste";
			menuPaste.Click += new EventHandler(PasteMenuClick);

			return new MenuCommand[] { mcAddCustomStoredProcedureColumn, menuSep, menuPaste };
    }

    public override MessageCollection Verify()
    {
      try
      {
        MessageCollection retval = new MessageCollection();
        retval.AddRange(base.Verify());

        //Check for duplicate names
        Hashtable nameList = new Hashtable();
        ReferenceCollection referenceCollection = (ReferenceCollection)this.Object;
        foreach(Reference reference in referenceCollection)
        {
          CustomStoredProcedureColumn customStoredProcedureColumn = (CustomStoredProcedureColumn)reference.Object;
          string name = customStoredProcedureColumn.Name.ToLower();
          if(nameList.ContainsKey(name))
            retval.Add(MessageTypeConstants.Error, string.Format(ValidationHelper.ErrorTextDuplicateName, name), this);
          else
            nameList.Add(name, "");
        }

        //CustomStoredProcedureColumn testCustomStoredProcedureColumn = (CustomStoredProcedureColumn)referenceCollection[0].Object;
        //if(!((CustomStoredProcedureColumn)testCustomStoredProcedureColumn.ParentViewRef.Object).Generated)
        //  return retval;

        return retval;

      }
      catch(Exception ex)
      {
        throw;
      }
    }

    public override bool DeleteObject()
    {
      return false;
    }

    public override void Refresh()
    {
      this.UserInterface = null;
    }

    #endregion

    #region Menu Handlers

    private void AddCustomStoredProcedureColumnMenuClick(object sender, System.EventArgs e)
    {
      try
      {
        CustomStoredProcedureColumn customStoredProcedureColumn = ((ModelRoot)this.Object.Root).Database.CustomStoredProcedureColumns.Add();
        ((ReferenceCollection)this.Object).Add(customStoredProcedureColumn.CreateRef());
        Reference customStoredProcedureRef = ((CustomStoredProcedure)((ModelObjectTreeNode)this.Node.Parent).Controller.Object).CreateRef();
        customStoredProcedureColumn.ParentRef = customStoredProcedureRef;
        this.OnItemChanged(this, new System.EventArgs());
      }
      catch(Exception ex)
      {
        throw;
      }
    }

		private void PasteMenuClick(object sender, System.EventArgs e)
		{
			try
			{
				if (Clipboard.ContainsData("ws.model.storedprocedurecolumn"))
				{
					XmlDocument document = new XmlDocument();
					document.LoadXml((string)Clipboard.GetData("ws.model.storedprocedurecolumn"));

					CustomStoredProcedureColumn newItem = ((CustomStoredProcedureColumnCollection)this.Object).Add();
					int id = newItem.Id;
					newItem.XmlLoad(document.DocumentElement);
					newItem.SetId(id);
					newItem.SetKey(Guid.NewGuid().ToString());
					newItem.Name = "[" + newItem.Name + "]";
					this.OnItemChanged(this, new System.EventArgs());
				}
			}
			catch (Exception ex)
			{				
				throw;
			}
		}

    #endregion

  }
}